package com.yzkj.cpjxc.business.system.interceptor;

import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.utils.CollectionHelp;
import com.yzkj.cpjxc.business.framework.utils.WebUtils;
import com.yzkj.cpjxc.business.domain.SysAuthority;
import com.yzkj.cpjxc.business.domain.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 权限拦截器
 */
public class PermissionInterceptor implements HandlerInterceptor {

	private Logger log = Logger.getLogger(PermissionInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		String action = request.getRequestURI();
		action = action.substring(action.lastIndexOf("/")+1);
		String ctx = WebUtils.getContextPath(request);
		
		// 1、 判断方法前是否有权限注解，有就做权限匹配，没有就放行
		if (method.isAnnotationPresent(Permission.class)) {
			// 2、判断用户是否登录
			SysUser currentUser = (SysUser) request.getSession().getAttribute(Constants.CURRENT_USER);
			if (currentUser == null) {
				PrintWriter out = response.getWriter();
				out.print("<script type='text/javascript'>top.location='"+ctx+"/'</script>");
				out.close();
				return false;
			}
			
			// 3、  取出注解的权限值
			Permission permission = method.getAnnotation(Permission.class);
			
			//测试使用======把有权限注解的添加到权限表中===开始=========
			/*long startTime = System.currentTimeMillis();//测试时间开始  此块代码影响运行性能
			SysAuthorityService sysAuthorityService = (SysAuthorityService)ContextUtils.getBean("sysAuthorityService");
			SysAuthority sa = new SysAuthority();
			sa.setAuthorityValue(permission.name());
			boolean isExist = sysAuthorityService.isExists(sa);
			if(!isExist){
				sa.setAuthorityId(IDUtils.genUUID());
				if(method.isAnnotationPresent(DoLog.class)){
					DoLog doLog = method.getAnnotation(DoLog.class);
					sa.setAuthorityName(doLog.cnContent());//操作内容
					sa.setRemark(doLog.cnContent());
				}else{
					sa.setAuthorityName("系统访问自动添加");
					sa.setRemark("系统访问自动添加");
				}
				sa.setAction(request.getServletPath());
				sa.setAuthorityType(SysAuthorityConstants.AUTH_TYPE_SYSTEM);
				sa.setAuthorityValue(permission.name());
				sa.setGrade("1");
				sa.setLevelCode(sysAuthorityService.getTopLevelSysAuthority().getLevelCode() + "-" + sa.getAuthorityId());
				sa.setParentId(sysAuthorityService.getTopLevelSysAuthority().getAuthorityId());
				sa.setSortNo("1");
				sa.setStatus(Constants.STATUS_ACTIVE);
				sysAuthorityService.create(sa);
			}
			//重新加载用户权限值
			//List<SysAuthority> sysAuthoritys = sysAuthorityService.getSysAuthoritysByUserId(currentUser.getUserId());
			//currentUser.setSysAuthoritys(sysAuthoritys);
			
			long endTime = System.currentTimeMillis();//毫秒  
			System.out.println(Float.toString((endTime - startTime) / 1000F) + "秒============================");//毫秒换算成秒除于1000 
			 */			
			//=======================结束================================
			
			
			// 4、  与系统管理员拥有的权限进行匹配
			boolean hasPrivilege = hasPrivilege(currentUser.getSysAuthoritys(), permission.name());

			if (hasPrivilege) { // 4.1 拥有
				return true;
			} else { // 4.2 不 拥有
				log.info("您没有操作" + permission.name() + "的权限!");
				// 弹出警告
				WebUtils.alertMsg(response, "您没有操作权限!");
				return false;
			}
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

	/**
	 * 是否有权限:true：有 ,false:无
	 * @param authorityValue
	 * @return
	 */
	private boolean hasPrivilege(List<SysAuthority> sysAuthoritys, String authorityValue) {
		boolean flag = false;
		if (CollectionHelp.isNotBank(sysAuthoritys) && StringUtils.isNotBlank(authorityValue)) {
			for(SysAuthority sas:sysAuthoritys){
				if (authorityValue.equals(sas.getAuthorityValue())) {
					flag = true;
				}
			}
		}
		return flag;
	}
}
